﻿using QRCoder;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Caching;
using System.Web.Http;
using YouWei.Api.Common;
using YouWei.Api.Models;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Models;
using YouWei.Infrastructure.Service;

namespace YouWei.Api.Controllers
{
    /// <summary>
    /// 车主卡
    /// </summary>
    public class UserCardController : BaseApiController
    {
        UserCardService cardService = new UserCardService();
        UserCardContentService contentService = new UserCardContentService();
        CardContentRelaService relaService = new CardContentRelaService();
        CouponUserRelaService cUserRelaService = new CouponUserRelaService();
        CouponService couponService = new CouponService();

        string FileUploadUrl = Utility.ConfigHelper.GetAppSettingValue("FileUploadUrl");

        /// <summary>
        /// 获取车主卡列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ResultData<List<UserCardInfo>> GetUserCardList(int userId)
        {
            ResultData<List<UserCardInfo>> result = ResultData<List<UserCardInfo>>.Success("查询成功");
            var list = cardService.GetListByUserId(userId);
            foreach (var item in list)
            {
                item.Icon = string.Format("{0}/{1}", FileUploadUrl, item.Icon);
                if (item.UpdatedDate.Year < 2019)
                {
                    item.UpdatedDate = DateTime.Now;
                }
            }
            result.data = list;
            return result;
        }

        /// <summary>
        /// 获取车主卡内容列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ResultData<UserCardModel> GetCardContents(int level)
        {
            ResultData<UserCardModel> result = ResultData<UserCardModel>.Success("查询成功");
            var data = cardService.GetCardByLevel(level).FirstOrDefault();
            data.Icon = string.Format("{0}/{1}", FileUploadUrl, data.Icon);

            var list = relaService.GetListByCardId(data.CardId);
            foreach (var item in list)
            {
                item.ContentDetailUrl = string.Format("{0}/{1}", FileUploadUrl, item.ContentDetailUrl);
                item.DetailUrl = string.Format("{0}/{1}", FileUploadUrl, item.DetailUrl);
                item.Icon = string.Format("{0}/{1}", FileUploadUrl, item.Icon);
            }
            data.Contents = list;

            result.data = data;
            return result;
        }

        /// <summary>
        /// 获取车主卡内容列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ResultData<UserCardModel> GetUserCardContentList(int cardId)
        {
            ResultData<UserCardModel> result = ResultData<UserCardModel>.Success("查询成功");
            var data = cardService.GetCardById(cardId);
            data.Icon = string.Format("{0}/{1}", FileUploadUrl, data.Icon);

            var list = relaService.GetListByCardId(data.CardId);
            foreach (var item in list)
            {
                item.ContentDetailUrl = string.Format("{0}/{1}", FileUploadUrl, item.ContentDetailUrl);
                item.DetailUrl = string.Format("{0}/{1}", FileUploadUrl, item.DetailUrl);
                item.Icon = string.Format("{0}/{1}", FileUploadUrl, item.Icon);
            }
            data.Contents = list;

            result.data = data;
            return result;
        }

        /// <summary>
        /// 获取洗车券
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<Coupon> GetCoupon(int userId)
        {
            if (userId < 1)
            {
                return ResultData<Coupon>.Error("参数错误");
            }

            //查询是否存在未过期的券
            var rela = cUserRelaService.GetActive(userId);
            if (rela != null)
            {
                var data = couponService.SingleOrDefault(rela.CouponID);
                return ResultData<Coupon>.Success(data);
            }

            //获取未使用的券
            var coupon = couponService.GetNoUse();
            if (coupon == null)
            {
                return ResultData<Coupon>.Error("洗车券不足，请联系客服");
            }

            //添加用户和券关联
            int days = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
            cUserRelaService.Insert(new CouponUserRela()
            {
                CardUserId = userId,
                CreateDate = DateTime.Now,
                ExpirationDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, days),
                UsedDate = DateTime.Now,
                UseStatus = 0,
                UsedStoreID = 0,
                CouponID=coupon.CouponID
            });

            //更新券为使用
            coupon.UpdateDate = DateTime.Now;
            coupon.CouponStatus = 1;
            couponService.Update(coupon);
            return ResultData<Coupon>.Success(coupon);
        }

        /// <summary>
        /// 获取二维码
        /// </summary>
        /// <param name="code">二维码图片</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public HttpResponseMessage GetQRCode(string code)
        {
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(code, QRCodeGenerator.ECCLevel.Q);
            QRCode qrCode = new QRCode(qrCodeData);
            Bitmap qrCodeImage = qrCode.GetGraphic(30, Color.White, Color.Black, null, 15, 6, false);
            var resp = new HttpResponseMessage(HttpStatusCode.OK);

            using (MemoryStream stream = new MemoryStream())
            {
                qrCodeImage.Save(stream, ImageFormat.Png);
                byte[] data = new byte[stream.Length];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(data, 0, Convert.ToInt32(stream.Length));
                resp.Content = new ByteArrayContent(data);
            }

            resp.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
            return resp;
        }
    }
}
